import _ from 'lodash';
import { getCssVariableValue } from '@/utils/utils';

/** 表头 */
export const tableColumns = [
  { code: 'id', name: '序号', width: 60, align: 'center', lock: true },
  { code: 'dispatchStationName', name: '电厂调度名', width: 180, align: 'left', lock: true },
  { code: 'dispatchEquipmentName', name: '设备调度名', width: 220, align: 'left' },
  { code: 'capacity', name: '机组容量', width: 100, align: 'center' },
  { code: 'maintenanceApplicationId', name: '检修申请单号', width: 100, align: 'center' },
  { code: 'equipmentTypeName', name: '设备类型', width: 100, align: 'center' },
  { code: 'equipmentStatus', name: '设备状态', width: 100, align: 'center' },
  { code: 'statusTypeName', name: '状态类型', width: 100, align: 'center' },
  { code: 'statusChangeReason', name: '状态改变原因', width: 100, align: 'center' },
  { code: 'startTime', name: '停运或启用开始时间', width: 140, align: 'center' },
  { code: 'endTime', name: '停运或启用结束时间', width: 140, align: 'center' },
];

export const tableFileterOptions = [
  { label: '机组', value: 3 },
  { label: '母线', value: 4 },
  { label: '变压器', value: 1 },
  { label: '线路', value: 5 },
  { label: '开关', value: 2 },
];

const DATA_MAP = {
  loadForecast: { name: '负荷预测', type: 'dashed', color: '#FD4F43' },
  eastPlanPowerForecast: { name: '东送计划预测', type: 'dashed', color: '#18A0FB' },
  nonMarketPowerForecast: { name: '非市场出力计划', type: 'dashed', color: '#18A0FB' },
  totalNewEnergyPowerForecast: { name: '全网新能源', type: 'dashed', color: '#30D485' },
  totalWindPowerForecast: { name: '全网风电', type: 'dashed', color: '#18A0FB' },
  totalPhotovoltaicPowerForecast: { name: '全网光伏', type: 'dashed', color: '#FFD60A' },
  positiveInfo: { name: '正备用', type: 'dashed', color: '#FD4F43' },
  negativeInfo: { name: '负备用', type: 'dashed', color: '#30D485' },
};

// 便于扩展
const TIME_KEY = 'time';
const POINTS = [
  { code: 'pointData1', name: 'D日' },
  { code: 'pointData2', name: 'D-1日' },
  { code: 'pointData3', name: 'D-2日' },
];
const POINT_COL = {
  code: TIME_KEY,
  name: '点位',
  getCellProps: (v) => {
    if (v?.length === 4) {
      return { style: { color: '#A7A8A9' } };
    }
  },
};
/** 渲染配置 */
const pointColumns = [
  { ...POINT_COL, width: 88 },
  ...POINTS.map((x) => ({ ...x, align: 'center' })),
];
export const myModuls = [
  {
    id: 'fhyc', // 数据标识
    name: '负荷预测',
    unit: '单位：MW',
    group: 'groupMx', // 图联动
    span: 12,
    columns: pointColumns,
    datakeys: ['loadForecast'],
    chartType: 'timeline', // 携带时间线
  },
  {
    id: 'dsjhyc', // 数据标识
    name: '东送计划预测',
    unit: '单位：MW',
    group: 'groupMx', // 图联动
    span: 12,
    columns: pointColumns,
    datakeys: ['eastPlanPowerForecast'],
    chartType: 'timeline', // 携带时间线
  },
  {
    id: 'fsccljh', // 数据标识
    name: '非市场出力计划',
    unit: '单位：MW',
    group: 'groupMx', // 图联动
    span: 12,
    columns: pointColumns,
    datakeys: ['nonMarketPowerForecast'],
    chartType: 'timeline', // 携带时间线
  },
  {
    id: 'xnyclyc', // 数据标识
    name: '新能源出力预测',
    unit: '单位：MW',
    group: 'groupMx', // 图联动
    span: 12,
    columns: [
      POINT_COL,
      { code: 'totalNewEnergyPowerForecast', name: '全网新能源', align: 'center' },
      { code: 'totalWindPowerForecast', name: '全网风电', align: 'center' },
      { code: 'totalPhotovoltaicPowerForecast', name: '全网光伏', align: 'center' },
    ],
    datakeys: [
      'totalNewEnergyPowerForecast',
      'totalWindPowerForecast',
      'totalPhotovoltaicPowerForecast',
    ],
    chartType: 'timeline', // 携带时间线
    select: POINTS[0].code,
    selectOption: POINTS.map((item, i) => ({
      value: item.code,
      label: i === 0 ? item.name : item.name + '预测',
    })),
  },
  {
    id: 'byxx', // 数据标识
    name: '备用信息',
    unit: '单位：MW',
    span: 24,
    columns: [
      POINT_COL,
      { code: 'positiveInfo', name: '正备用', align: 'center' },
      { code: 'negativeInfo', name: '负备用', align: 'center' },
    ],
    datakeys: ['positiveInfo', 'negativeInfo'],
  },
];

const chartBase = () => {
  return {
    dataset: { dimensions: [], source: [] },
    grid: { top: 12, left: 48, bottom: 75, right: 75 },
    legend: {
      textStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
    },
    tooltip: {},
    dataZoom: [
      {
        type: 'slider',
        bottom: 26,
        start: 0,
        end: 100,
        height: 20,
        show: true,
        backgroundColor: getCssVariableValue('--bg-form'),
        dataBackground: {
          dataBackground: {
            areaStyle: { opacity: 0 },
            lineStyle: { opacity: 0 },
          },
        },
        selectedDataBackground: {
          areaStyle: {
            color: getCssVariableValue('--font-primary'),
            opacity: 0.15,
          },
          lineStyle: { color: 'transparent' },
        },
        borderColor: 'transparent',
        handleStyle: {
          color: getCssVariableValue('--bg-form'),
          borderColor: getCssVariableValue('--bd'),
        },
        brushSelect: false,
        showDetail: false,
      },
    ],
    xAxis: [
      {
        type: 'category',
        formatter: (v) => v.slice(4),
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisLine: {
          lineStyle: {
            type: 'solid',
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisTick: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
      },
    ],
    series: [],
  };
};

/** 数据处理 */
export const handleRenderData = (_dataSource) => {
  const fmtDatesMap = ({ data, json, key }) => {
    // 按时间维度 => Json对象
    let result = { ...json };
    for (const _date in data) {
      const pointList = data[_date] || []; // 点位数据
      const date = _date.replace(/[-]/g, ''); // 格式化日期
      let sum = 0; // 单日总和
      pointList.map(({ xAxis, value }) => {
        const val = +value || 0;
        const id = `${date} ${xAxis}`;
        sum += val;
        if (!result.data[id]) {
          result.data[id] = { id, date, [TIME_KEY]: xAxis };
        }
        result.data[id][key] = val.toFixed(2); // 点位值 统一保留两位
      });
      // 计算日平均值
      if (!result.avg[date]) {
        result.avg[date] = { id: date, [TIME_KEY]: date };
      }
      result.avg[date][key] = (sum / (pointList.length || 1)).toFixed(2);
    }
    return result;
  };
  const result = _.cloneDeep(myModuls);
  if (!_dataSource) return result;
  return result.map((item) => {
    let tableData; // 表格数据
    let chartOption = _.cloneDeep(chartBase()); // 图表配置
    const { datakeys = [] } = item;
    const len = datakeys?.length;
    chartOption.series = datakeys.map((key) => DATA_MAP[key]);
    if (item.chartType === 'timeline') {
      // 时间线图，含预测维度
      chartOption.timeline = { title: '预测版本', data: POINTS.map((x) => x.name) };
      if (len > 1) {
        // 长度大于1时，表格列=图系列
        tableData = {}; // 有切换操作，映射存object
        let timelineOptions = [];
        const dimensions = ['id', ...datakeys];
        POINTS.map((point) => {
          const pointCode = point.code;
          let json = { data: {}, avg: {} };
          for (const key of datakeys) {
            json = fmtDatesMap({ key, json, data: _dataSource?.[key]?.[pointCode] || {} });
          }
          const chartData = Object.values(json.data);
          timelineOptions.push({ dataset: { dimensions, source: chartData } });
          let pointTableData = [];
          for (const date in _.groupBy(chartData, 'date')) {
            pointTableData.push({
              ...json.avg[date],
              children: chartData,
            });
          }
          tableData[pointCode] = pointTableData;
        });
        chartOption.timeline.options = timelineOptions;
      } else {
        // 系列长度为1时，表格列=预测维度
        tableData = [];
        let json = { data: {}, avg: {} };
        POINTS.map((point) => {
          const pointCode = point.code;
          const _data = _dataSource?.[datakeys[0]]?.[pointCode] || {};
          json = fmtDatesMap({ key: pointCode, json, data: _data });
        });
        const chartData = Object.values(json.data);
        const timelineOptions = POINTS.map((point) => ({
          dataset: { dimensions: ['id', point.code], source: chartData },
        }));
        chartOption.timeline.options = timelineOptions;
        for (const date in _.groupBy(chartData, 'date')) {
          tableData.push({
            ...json.avg[date],
            children: chartData,
          });
        }
      }
    } else {
      // 2. 普通图形，表格列=图系列
      tableData = [];
      chartOption.grid.right = 10;
      let json = { data: {}, avg: {} };
      const dimensions = ['id', ...datakeys];
      for (const key of datakeys) {
        const _data = _dataSource?.[key] || {};
        json = fmtDatesMap({ key, json, data: _data });
      }
      const chartData = Object.values(json.data);
      chartOption.dataset = { dimensions, source: chartData };
      for (const date in _.groupBy(chartData, 'date')) {
        tableData.push({
          ...json.avg[date],
          children: chartData,
        });
      }
    }
    return {
      ...item,
      tableData, // 表格数据
      chartOption, // 图配置
    };
  });
};

// 导出数据
export const handleExportData = (_charts, _dataSource) => {
  let result = [];
  _charts.map((item) => {
    const { datakeys = [] } = item;
    if (item.chartType === 'timeline') {
      const options = item?.chartOption?.timeline?.options;
      datakeys.map((key) => {
        const sheetName = DATA_MAP?.[key]?.name || ''; // 名称
        let temp = { name: sheetName, data: [['类型']] };
        POINTS.map((p, i) => {
          const _name = p.name;
          const _data = options?.[i]?.dataset?.source || [];
          const _values = _data.map((x) => {
            i === 0 && temp.data[0].push(x.id.slice(4));
            const vkey = datakeys.length > 1 ? key : p.code;
            return x[vkey];
          });
          temp.data.push([_name, ..._values]);
        });
        result.push(temp);
      });
    } else {
      const sheetName = item.name;
      const _data = item?.chartOption?.dataset?.source;
      let temp = { name: sheetName, data: [['类型']] };
      datakeys.map((key, i) => {
        const _name = DATA_MAP?.[key]?.name || '';
        const _values = _data.map((x) => {
          i === 0 && temp.data[0].push(x.id.slice(4));
          return x[key];
        });
        temp.data.push([_name, ..._values]);
      });
      result.push(temp);
    }
  });
  return result;
};
